<template>
  <div class="job-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>岗位管理</h2>
      <el-button type="primary" :icon="Plus" @click="handleAddJob">发布新岗位</el-button>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input v-model="searchKeyword" placeholder="请输入岗位名称或描述" clearable style="width: 200px"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="statusFilter" placeholder="选择状态" style="width: 120px">
            <el-option label="全部" value="all" />
            <el-option label="招聘中" value="active" />
            <el-option label="已下线" value="inactive" />
            <el-option label="草稿" value="draft" />
          </el-select>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" @change="handleDateFilter" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 岗位列表 -->
    <el-card class="jobs-table-card">
      <!-- 批量操作 -->
      <div v-if="selectedJobs.length > 0" class="batch-actions">
        <span>已选择 {{ selectedJobs.length }} 个岗位</span>
        <el-button size="small" type="success" @click="handleBatchOnline">批量上线</el-button>
        <el-button size="small" type="warning" @click="handleBatchOffline">批量下线</el-button>
        <el-button size="small" type="primary" @click="handleBatchTop">批量置顶</el-button>
        <el-button size="small" type="danger" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <el-table v-loading="loading" :data="jobs" @selection-change="handleSelectionChange" row-key="jobId">
        <el-table-column type="selection" width="55" />

        <el-table-column prop="jobName" label="岗位名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="jobDescription" label="岗位描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="location" label="工作地点" width="120" />
        <el-table-column prop="salary" label="薪资" width="120" />
        <el-table-column prop="jobStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.jobStatus)">
              {{ getStatusText(row.jobStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="isTop" label="置顶" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.isTop" type="warning" size="small">置顶</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="applicationCount" label="投递数" width="80" />
        <el-table-column prop="viewCount" label="浏览数" width="80" />
        <el-table-column prop="createTime" label="发布时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" type="primary" @click="handleEditJob(row)">编辑</el-button>
              <el-button size="small" :type="row.jobStatus === 'active' ? 'warning' : 'success'"
                @click="handleToggleStatus(row)">
                {{ row.jobStatus === 'active' ? '下线' : '上线' }}
              </el-button>
              <el-button size="small" :type="row.isTop ? 'info' : 'primary'" @click="handleToggleTop(row)">
                {{ row.isTop ? '取消置顶' : '置顶' }}
              </el-button>
              <el-button size="small" type="danger" @click="handleDeleteJob(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="totalJobs" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 岗位编辑对话框 -->
    <JobEditDialog v-model="jobDialogVisible" :job-data="currentJobData" @success="handleJobSuccess" />


    <!-- 确认操作对话框 -->
    <el-dialog v-model="confirmDialogVisible" :title="confirmDialogTitle" width="400px" :close-on-click-modal="false">
      <div class="confirm-content">
        <div class="confirm-icon">
          <el-icon :size="48" :color="confirmDialogIconColor">
            <component :is="confirmDialogIcon" />
          </el-icon>
        </div>
        <div class="confirm-message">
          {{ confirmDialogMessage }}
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleConfirmCancel">取消</el-button>
          <el-button :type="confirmDialogButtonType" :loading="confirmLoading" @click="handleConfirmOk">
            {{ confirmDialogButtonText }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useEnterpriseStore } from '@/store/job/modules/enterprise'
import { useAppStore } from '@/store/job/modules/app'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Briefcase, Check, Document, View, Search, Refresh, Warning, InfoFilled, Delete } from '@element-plus/icons-vue'
import JobEditDialog from '@/components/job/JobEditDialog.vue'
import { getJobList, updateJobStatus, updateJobTopStatus, deleteJob, batchOperateJobs } from '@/api/enterprise'

const enterpriseStore = useEnterpriseStore()
const appStore = useAppStore()

// 岗位列表数据
const jobs = ref([])
const loading = ref(false)
const totalJobs = ref(0)

// 确认弹窗相关
const confirmDialogVisible = ref(false)
const confirmDialogTitle = ref('')
const confirmDialogMessage = ref('')
const confirmDialogIcon = ref('')
const confirmDialogIconColor = ref('')
const confirmDialogButtonText = ref('')
const confirmDialogButtonType = ref('primary')
const confirmLoading = ref(false)
const currentConfirmAction = ref(null)
const currentConfirmJob = ref(null)

// 获取岗位列表
const fetchJobs = async () => {
  try {
    loading.value = true
    const params = {
      keyword: searchKeyword.value,
      status: statusFilter.value !== 'all' ? statusFilter.value : undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    }

    const response = await getJobList(params)
    jobs.value = response?.data?.list || response?.list || []
    totalJobs.value = response?.data?.total || response?.total || 0
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(async () => {
  try {
    await fetchJobs()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})

// 搜索和筛选
const searchKeyword = ref('')
const statusFilter = ref('all')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 选中的岗位
const selectedJobs = ref([])

// 对话框状态
const jobDialogVisible = ref(false)
const currentJobData = ref({})

// 岗位表单
const jobForm = reactive({
  jobName: '',
  jobDescription: '',
  jobRequirements: '',
  jobStatus: 'active'
})

// 表单验证规则
const jobFormRules = {
  jobName: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ],
  jobDescription: [
    { required: true, message: '请输入岗位描述', trigger: 'blur' }
  ],
  jobRequirements: [
    { required: true, message: '请输入岗位要求', trigger: 'blur' }
  ]
}


// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchJobs()
}

// 重置筛选
const handleReset = () => {
  searchKeyword.value = ''
  statusFilter.value = 'all'
  dateRange.value = []
  currentPage.value = 1
  fetchJobs()
}

// 日期筛选
const handleDateFilter = () => {
  handleSearch()
}

// 筛选处理
const handleFilter = () => {
  handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchJobs()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchJobs()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedJobs.value = selection
}

// 岗位操作
const handleAddJob = () => {
  currentJobData.value = {}
  jobDialogVisible.value = true
}

const handleEditJob = (job) => {
  currentJobData.value = { ...job }
  jobDialogVisible.value = true
}

// 岗位操作成功回调
const handleJobSuccess = (newJobData) => {
  // 刷新岗位列表
  fetchJobs()

  // 如果是新创建的岗位，显示成功消息
  if (newJobData && newJobData.jobId) {
    ElMessage.success(`岗位"${newJobData.jobName}"发布成功！`)
  }
}


const handleToggleStatus = async (job) => {
  const newStatus = job.jobStatus === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '上线' : '下线'

  // 设置弹窗内容
  currentConfirmAction.value = 'toggleStatus'
  currentConfirmJob.value = job
  confirmDialogTitle.value = `${action}岗位`
  confirmDialogMessage.value = `确定要将岗位"${job.jobName}"${action}吗？`
  confirmDialogIcon.value = newStatus === 'active' ? 'Check' : 'Warning'
  confirmDialogIconColor.value = newStatus === 'active' ? '#67c23a' : '#e6a23c'
  confirmDialogButtonText.value = `确定${action}`
  confirmDialogButtonType.value = newStatus === 'active' ? 'success' : 'warning'
  confirmDialogVisible.value = true
}

const handleToggleTop = async (job) => {
  const newTopStatus = !job.isTop
  const action = newTopStatus ? '置顶' : '取消置顶'

  // 设置弹窗内容
  currentConfirmAction.value = 'toggleTop'
  currentConfirmJob.value = job
  confirmDialogTitle.value = `${action}岗位`
  confirmDialogMessage.value = `确定要将岗位"${job.jobName}"${action}吗？`
  confirmDialogIcon.value = 'InfoFilled'
  confirmDialogIconColor.value = '#409eff'
  confirmDialogButtonText.value = `确定${action}`
  confirmDialogButtonType.value = 'primary'
  confirmDialogVisible.value = true
}

// 删除单个岗位
const handleDeleteJob = async (job) => {
  // 设置弹窗内容
  currentConfirmAction.value = 'delete'
  currentConfirmJob.value = job
  confirmDialogTitle.value = '删除岗位'
  confirmDialogMessage.value = `确定要删除岗位"${job.jobName}"吗？此操作不可恢复！`
  confirmDialogIcon.value = 'Delete'
  confirmDialogIconColor.value = '#f56c6c'
  confirmDialogButtonText.value = '确定删除'
  confirmDialogButtonType.value = 'danger'
  confirmDialogVisible.value = true
}

// Dialog事件处理
const handleConfirmOk = async () => {
  if (!currentConfirmJob.value || !currentConfirmAction.value) return

  confirmLoading.value = true

  try {
    const job = currentConfirmJob.value
    const action = currentConfirmAction.value

    if (action === 'toggleStatus') {
      const newStatus = job.jobStatus === 'active' ? 'inactive' : 'active'
      await updateJobStatus(job.jobId, newStatus)
      ElMessage.success(`${newStatus === 'active' ? '上线' : '下线'}成功`)
    } else if (action === 'toggleTop') {
      const newTopStatus = !job.isTop
      await updateJobTopStatus(job.jobId, newTopStatus)
      ElMessage.success(`${newTopStatus ? '置顶' : '取消置顶'}成功`)
    } else if (action === 'delete') {
      await deleteJob(job.jobId)
      ElMessage.success('删除成功')
    }

    fetchJobs() // 刷新列表
    confirmDialogVisible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    confirmLoading.value = false
  }
}

const handleConfirmCancel = () => {
  confirmDialogVisible.value = false
  currentConfirmAction.value = null
  currentConfirmJob.value = null
}

const getStatusType = (status) => {
  const statusMap = {
    active: 'success',
    inactive: 'info',
    draft: 'warning',
    expired: 'danger'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    active: '招聘中',
    inactive: '已下线',
    draft: '草稿',
    expired: '已过期'
  }
  return statusMap[status] || '未知'
}


// 批量操作
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedJobs.value.length} 个岗位吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 执行批量删除
    const jobIds = selectedJobs.value.map(job => job.jobId)
    await batchOperateJobs(jobIds, 'delete')

    ElMessage.success('批量删除成功')
    selectedJobs.value = []
    fetchJobs() // 刷新列表
  } catch (error) {
    // 用户取消操作
  }
}

const handleBatchOffline = async () => {
  try {
    await ElMessageBox.confirm(`确定要下线选中的 ${selectedJobs.value.length} 个岗位吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 执行批量下线
    const jobIds = selectedJobs.value.map(job => job.jobId)
    await batchOperateJobs(jobIds, 'offline')

    ElMessage.success('批量下线成功')
    selectedJobs.value = []
    fetchJobs() // 刷新列表
  } catch (error) {
    // 用户取消操作
  }
}

const handleBatchOnline = async () => {
  try {
    await ElMessageBox.confirm(`确定要上线选中的 ${selectedJobs.value.length} 个岗位吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 执行批量上线
    const jobIds = selectedJobs.value.map(job => job.jobId)
    await batchOperateJobs(jobIds, 'online')

    ElMessage.success('批量上线成功')
    selectedJobs.value = []
    fetchJobs() // 刷新列表
  } catch (error) {
    // 用户取消操作
  }
}

const handleBatchTop = async () => {
  try {
    await ElMessageBox.confirm(`确定要置顶选中的 ${selectedJobs.value.length} 个岗位吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 执行批量置顶
    const jobIds = selectedJobs.value.map(job => job.jobId)
    await batchOperateJobs(jobIds, 'top')

    ElMessage.success('批量置顶成功')
    selectedJobs.value = []
    fetchJobs() // 刷新列表
  } catch (error) {
    // 用户取消操作
  }
}

</script>

<style scoped>
.job-management {
  padding: 20px;
}

/* 确认弹窗样式 */
.confirm-content {
  text-align: center;
  padding: 20px 0;
}

.confirm-icon {
  margin-bottom: 16px;
}

.confirm-message {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filter-card {
  margin-bottom: 20px;
}

.jobs-table-card {
  margin-bottom: 20px;
}

.batch-actions {
  margin: 15px 0;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}


.no-data {
  text-align: center;
  padding: 40px 0;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  flex-wrap: nowrap;
  gap: 4px;
  align-items: center;
}

.action-buttons .el-button {
  flex-shrink: 0;
  min-width: auto;
  padding: 4px 8px;
  font-size: 12px;
}
</style>